import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Solution47 {
    boolean[] vis;

    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> list = new ArrayList<>();

        Arrays.sort(nums);
        vis = new boolean[nums.length];
        backtrack(res, list, nums, 0);
        return res;
    }

    public List<List<Integer>> permuteUnique2(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        for (int num : nums) {
            list.add(num);
        }
        Collections.sort(list);
        perm(res, list, 0, nums.length - 1);

        return res;
    }

    private void backtrack(List<List<Integer>> res, List<Integer> perm, int[] nums, int idx) {
        if (idx == nums.length) {
            res.add(new ArrayList<>(perm));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (vis[i] || (i > 0 && nums[i] == nums[i - 1] && !vis[i - 1])) {
                continue;
            }
            perm.add(nums[i]);
            vis[i] = true;
            backtrack(res, perm, nums, idx + 1);
            vis[i] = false;
            perm.remove(idx);
        }
    }

    private void perm(List<List<Integer>> res, List<Integer> nums, int start, int end) {
        if (start == end) {
            res.add(new ArrayList<>(nums));
            return;
        }
        for (int i = start; i <= end; i++) {
            if (i == start) {
                perm(res, nums, start + 1, end);
            } else {
                if (i > 0 && nums.get(i).equals(nums.get(i - 1))) {
                    continue;
                }
                if (nums.get(i).equals(nums.get(start))) {
                    continue;
                }
                Collections.swap(nums, i, start);
                perm(res, nums, start + 1, end);
                Collections.swap(nums, i, start);
            }
        }
    }
}
